// 通用工具
import store from '@/store'
import vm from '@/main'
export function param(urlIn, data) { // get请求的参数拼接 | 对象转请求串
  let url = ''
  for (var k in data) {
    let value = data[k] !== undefined ? data[k] : ''
    url += '&' + k + '=' + encodeURIComponent(value)
  }
  url = url ? url.substring(1) : ''
  urlIn += (urlIn.indexOf('?') < 0 ? '?' : '&') + url
  return urlIn
}
export function isStatus(callback, type) { // 控制端执行
  var mqtt = store.state.mqttStatus
  // console.log(mqtt.status,!!mqtt);
  if (mqtt.status === type) {
    if (!!mqtt) {
      callback()
    } else {
      vm.$eventBus.$emit("mqtt_status", true)
    }
  } else {
    console.log(mqtt.status , type);
  }
}

export function getDay(day) { // 获取指定天数前的时间戳
  let days = +new Date()
  return days + 1000 * 60 * 60 * 24 * day
}

export function getLocalTime(nS, index) { // 时间戳转字符串 2 有时间 1 无时间
  //    var time = new Date(parseInt(nS)).toLocaleString();
  // console.log(nS);
  //    var reg =  new RegExp("(/)", "g");
  //    var reg_time =  new RegExp("(上午|下午)", "g");
  //    return time.replace(reg,'-').replace(reg_time,'');
  var now = new Date(parseInt(nS));

  var year = now.getFullYear();
  var month = now.getMonth() + 1;
  var date = now.getDate();
  var hour = now.getHours();
  var minute = now.getMinutes();
  var second = now.getSeconds();
  return index === 2 ? year + "-" + month + "-" + date + "   " + hour + ":" + minute + ":" + second : year + "-" +
    month +
    "-" + date;
}

export function typeOf(obj) { // 数组类型判断
  let res = Object.prototype.toString.call(obj).split(' ')[1]
  res = res.substring(0, res.length - 1).toLowerCase()
  console.log(res)
  return res
}

export function flatten(arr) { // 数组扁平化
  while (arr.some(item => Array.isArray(item))) {
    arr = [].concat(...arr);
  }
  return arr;
}

export function deepClone(obj) { // 简单深拷贝
  if (typeof obj !== 'object') return
  var newObj = obj instanceof Array ? [] : {}
  for (let key in obj) {
    if (obj.hasOwnProperty(key)) {
      newObj[key] = typeof obj[key] === 'object' ? deepClone(obj[key]) : obj[key]
    }
  }
  return newObj
}

export function parseParam(url) { // 将带参数的url 参数转为json对象
  const paramsStr = /.+\?(.+)$/.exec(url)[1]
  const paramsArr = paramsStr.split('&')
  let paramsObj = {}

  paramsArr.forEach(param => {
    if (/=/.test(param)) {
      let [key, val] = param.split('=')
      val = decodeURIComponent(val) // 解码
      val = /^\d+$/.test(val) ? +val : val

      if (paramsObj.hasOwnProperty(key)) {
        paramsObj[key] = [].concat(paramsObj[key], val)
      } else {
        paramsObj[key] = val
      }
    } else {
      paramsObj[param] = true
    }
  })
  // console.log(paramsObj)
  return paramsObj
}
